package com.wsc.goods.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wsc.goods.domain.Product;
import com.wsc.goods.service.ProductService;
import com.wsc.tools.AjaxResult;
import com.wsc.tools.PageQuery;
import com.wsc.tools.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wsc
 * @since 2019-11-20
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    ProductService productService;

    @PostMapping("/save")
    public AjaxResult save(@RequestBody Product product){
        try {
            if(product.getId() == null || product.getId() <=0){

                productService.saveProduct(product);
            }else {
                productService.updateProduct(product);
            }
            return AjaxResult.getInstance().setMsg("保存成功");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.getInstance().setCode(500).setMsg("保存失败");
        }

    }


    /**
     * 显示商品列表
     * @return 带分页的商品列表
     */
    @GetMapping("/show")
    public PageResult<Product> show(@RequestBody PageQuery pageQuery){
        IPage<Product> iPage = productService.page(new Page<Product>(pageQuery.getPage(),pageQuery.getRows())
        ,new QueryWrapper<Product>().like("name",pageQuery.getKeywords())
        .or().like("subName",pageQuery.getKeywords()).orderByDesc("createTime"));
        return new PageResult<Product>(iPage.getTotal(),iPage.getRecords());
    }

}

